package cn.itcast.demo.lock;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
public class SimpleRedisLock implements RedisLock {
    /**
     * 锁的名称
     */
    private final String key;
    /**
     * redis模板
     */
    private final StringRedisTemplate redisTemplate;

    private final String VALUE_PREFIX = UUID.randomUUID().toString();

    public SimpleRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean tryLock(long releaseTime) {
        // 当前线程的锁标示
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 判断结果
        return BooleanUtils.isTrue(boo);
    }

    @Override
    public void unlock() {
        // 当前线程的锁标示
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 获取redis中的锁标示
        String cacheValue = redisTemplate.opsForValue().get(key);
        // 比较
        if(StringUtils.equals(value, cacheValue)){
            // 一致，是自己的锁，删除
            redisTemplate.delete(key);
        }
    }
}
